package interview.lock;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch用法：定义一个CountDownLatch对象指定数值，该数值代表线程数量。当每一个线程执行完毕，调用countDown()方法使数值减一，
 *                     当减为0时，继续执行await()一下的代码。该过程是一个线程数量递减的过程
 *
 *
 * **/

public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i=1;i<=6;i++){
            new Thread(()->{
                countDownLatch.countDown();
                System.out.println(Thread.currentThread().getName()+"国被灭");
            },CountryEnum.item(i).getCountryName()).start();
        }
        System.out.println("before await.......");
        try {
            countDownLatch.await(); //主线程在这里会被阻塞
            System.out.println("after await.......");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("秦国扫六合！！");
    }

}

enum CountryEnum{

    ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FORE(4,"韩"),FIVE(5,"赵"),SIX(6,"魏"),SEVEN(7,"秦");

    private Integer number;

    private String countryName;

    CountryEnum(Integer number, String countryName) {
        this.number = number;
        this.countryName = countryName;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public static CountryEnum item(int index){
        CountryEnum[] countryEnums = CountryEnum.values();
        for (CountryEnum item:countryEnums){
            if(item.getNumber()==index){
                return item;
            }
        }
        return null;
    }
}